package com.fancon.android.gardenjokesx.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.fancon.android.emoji.widget.RichEditText;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.ReportErrors;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.CheckValidate;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class EditProfileActivity extends GardenJokesBaseActivity implements OnClickListener, OnFocusChangeListener{
	private View backBtn;
	// U04 views
	private RichEditText mEditFirstName;
	public Boolean isFirstTime = true;

	private RichEditText mEditLastName;
	private EditText mEditEmail;
	private EditText mEditUserName;
	private EditText mEditPassword;
	private EditText mEditPhoneNumber;
	private RichEditText mEditBio;
	private User userProfile;
	private Button btnSave;
	//private Boolean toogle = false;
	private ReportErrors reportError;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mesx_edit_profile_u04);
		TextView title = (TextView) findViewById(R.id.action_bar_textview_title);
		title.setText(getText(R.string.edit_profile_title));
		
		backBtn = findViewById(R.id.action_bar_button_back);
		backBtn.setOnClickListener(this);
		btnSave = (Button) findViewById(R.id.save);
		btnSave.setOnClickListener(this);
		
		mEditFirstName = (RichEditText) findViewById(R.id.u04_editFirstName);
		//Button emoji = (Button) findViewById(R.id.emoji_btn);
		//mEditFirstName.bindKeyBoard(emoji, false);

		mEditLastName = (RichEditText) findViewById(R.id.u04_editLastName);
		mEditEmail = (EditText) findViewById(R.id.u04_editEmail);
		mEditUserName = (EditText) findViewById(R.id.u04_editUserName);
		mEditUserName.setEnabled(false);
		mEditPassword = (EditText) findViewById(R.id.u04_editPassword);
		mEditPhoneNumber = (EditText) findViewById(R.id.u04_editPhoneNumber);
		mEditBio = (RichEditText) findViewById(R.id.u04_editBio);
		
		bindFocusChange();
		UserRequest request = new UserRequest("u0304", EditProfileActivity.this);
		getGlobalState().getRequestQueue().addRequest(request);
	}
	private void bindFocusChange(){
		mEditFirstName.setOnFocusChangeListener(this);
		mEditLastName.setOnFocusChangeListener(this);
		mEditEmail.setOnFocusChangeListener(this);
		mEditUserName.setOnFocusChangeListener(this);
		mEditPassword.setOnFocusChangeListener(this);
		mEditPhoneNumber.setOnFocusChangeListener(this);
		mEditBio.setOnFocusChangeListener(this);
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == backBtn){
			finish();
		}
		if(v == btnSave){
			// Update user profile
			String firstName = mEditFirstName.getRichText().toString();
			String lastName = mEditLastName.getRichText().toString();
			String email = mEditEmail.getText().toString();
			String username = mEditUserName.getText().toString();
			String password = mEditPassword.getText().toString();
			String phone = mEditPhoneNumber.getText().toString();
			String about = mEditBio.getRichText().toString();
			Log.d("about", about.length() + "");
			if (firstName != null && firstName.length() > 16) {
				
				mEditFirstName.requestFocus();
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_first_name),
						Constant.MAX_LENGTH_PASS_OR_USERNAME));
				return;
			}
			if (lastName.length() > 16) {
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_last_first),
						Constant.MAX_LENGTH_PASS_OR_USERNAME));
				mEditLastName.requestFocus();
				return;
			}

			// Check email valid
			if (email.length() == 0) {
				showErrorDialog(getString(R.string.ERR5001,
						getString(R.string.u04_email)));
				mEditEmail.requestFocus();
				return;
			}
			if (!CheckValidate.checkEmailFormat(email)) {
				showErrorDialog(getString(R.string.ERR5005,
						getString(R.string.u04_email)));
				mEditEmail.requestFocus();
				return;
			}  
			

			// Check username

			if (username.length() == 0) {
				showErrorDialog(getString(R.string.ERR5001,
						getString(R.string.u04_user_name)));
				mEditUserName.requestFocus();
				return;
			}

			if (username.length() < 4) {
				showErrorDialog(getString(R.string.ERR5002,
						getString(R.string.u04_user_name),
						Constant.MIN_LENGTH_PASS_OR_USERNAME));
				mEditUserName.requestFocus();
				return;
			}

			if (username.length() > 16) {
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_user_name),
						Constant.MAX_LENGTH_PASS_OR_USERNAME));
				mEditUserName.requestFocus();
				return;
			}
			if (!CheckValidate.checkAlphabetOrNumber(username)) {
				showErrorDialog(getString(R.string.ERR5004,
						getString(R.string.u04_user_name)));
				mEditUserName.requestFocus();
				return;
			}
			
			// Check password
			if (password.length() == 0) {
				showErrorDialog(getString(R.string.ERR5001,
						getString(R.string.u04_password)));
				mEditPassword.requestFocus();
				return;
			}

			if (password.length() < 4) {
				showErrorDialog(getString(R.string.ERR5002,
						getString(R.string.u04_password),
						Constant.MIN_LENGTH_PASS_OR_USERNAME));
				mEditPassword.requestFocus();
				
				return;
			}

			if (password.length() > 16) {
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_password),
						Constant.MAX_LENGTH_PASS_OR_USERNAME));
				mEditPassword.requestFocus();
				return;
			}
			if (!CheckValidate.checkAlphabetOrNumber(password)) {
				showErrorDialog(getString(R.string.ERR5004,
						getString(R.string.u04_password)));
				mEditPassword.requestFocus();
				return;
			}

			// Check Phone number
			if (phone.length() > 32) {
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_phone_number),
						Constant.MAX_LENGTH_PHONE));
				mEditPhoneNumber.requestFocus();
				return;
			}

			// Check about
			if (mEditBio.getRichText() != null && mEditBio.getRichText().length() > 150) {
				showErrorDialog(getString(R.string.ERR5003,
						getString(R.string.u04_bio), Constant.MAX_LENGTH_ABOUT));
				mEditBio.requestFocus();
				return;
			}
			CheckValidRequest request = new CheckValidRequest("editProfile", EditProfileActivity.this, firstName, lastName, email, username,
					password, phone, about);
			getGlobalState().getRequestQueue().addRequest(request);
		}
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		if (v instanceof RichEditText) {
			if (hasFocus && keyboardHeight > 0) {
				showEmojiPanel(keyboardHeight);
			}
		} else {
			if (hasFocus) {
				hideEmojiPanel();
			}
		}
	}
	
	class UserRequest extends RequestUI {
		private Activity context;
		private Boolean isFirst = true;
		private FanconProgressBar progress;

		public UserRequest(Object key, Activity activity) {
			super(key, activity);
			context = activity;
			if (isFirst) {
				progress = FanconProgressBar.show(context, context.getString(R.string.common_loading));
			}

		}

		@Override
		public void execute() {
			// TODO Auto-generated method stub
			
			List<NameValuePair> youDataValuePairs = new ArrayList<NameValuePair>(
					1);
			youDataValuePairs.add(new BasicNameValuePair("user_id", UserUtil.getInfoUserLogin(context).getUser_id()));
			GardenJokesApiConnect api = new GardenJokesApiConnect(context);
			String youProfile = "";
			youProfile = api.execGet(context, GardenJokesApiConnect.GROUP_U,
					"getUserProfile", youDataValuePairs);

			JsonPaser jP = new JsonPaser();
			userProfile = new User();
			userProfile = null;
			Log.v("youData", youProfile);
			if (youProfile.length() > 0) {
				userProfile = jP.getUser(youProfile);
			} else {
				btnSave.setClickable(false);
			}
			Log.v("StringResult", youProfile);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub

			if (userProfile != null) {

				displayUserProfile(userProfile);
			}

			if (progress != null) {
				progress.dismiss();
			}
			isFirst = false;

		}

	}
	
	/**
	 * Display user profile
	 * 
	 * @param user
	 */
	private void displayUserProfile(User user) {
		if (user != null) {
			try {
				if (user.getFirst_name() != null) {
					mEditFirstName.setText(URLDecoder.decode(user.getFirst_name(), "UTF-8"));
				}
				if (user.getLast_name() != null) {
					mEditLastName.setText(URLDecoder.decode(user.getLast_name(), "UTF-8"));
				}
				if (user.getEmail() != null) {
					mEditEmail.setText(URLDecoder.decode(user.getEmail(), "UTF-8"));
				}
				if (user.getPhone() != null) {
					mEditPhoneNumber.setText(URLDecoder.decode(user.getPhone(), "UTF-8"));
				}
				if (user.getUser_name() != null) {
					mEditUserName.setText(URLDecoder.decode(user.getUser_name(), "UTF-8"));
				}
				// TODO : password must be get from local DB
				User userLoged = UserUtil.getInfoUserLogin(this);
		
				mEditPassword.setText(userLoged.getPassword());
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			String about = "";
			about = user.getAbout();
			if (about != null && about.length() != 0) {
				try {
					about = URLDecoder.decode(about, "UTF-8");
					mEditBio.setText(about);
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
//			aboutLength = about.length();
//			mTvAbout.setText(aboutLength + "/150");
		}
		
	}
	
	
	private class CheckValidRequest extends RequestUI {

		private Activity context;
		private FanconProgressBar mProgressDialog;
//		private String firstName;
//		private String lastName;
//		private String email;
//		private String username;
//		private String password;
//		private String phone;
//		private String about;
//		private Boolean isFirst = true;
		Boolean report = false;
		List<NameValuePair> youProfileValuePairs = new ArrayList<NameValuePair>(
				7);

		public CheckValidRequest(Object key, Activity activity,
				String firstName, String lastName, String email,
				String username, String password, String phone, String about) {
			super(key, activity);
			context = activity;
//			isFirst = true;
			mProgressDialog = FanconProgressBar.show(context, context.getString(R.string.common_loading));
//			this.firstName = firstName;
//			this.lastName = lastName;
//			this.email = email;
//			this.password = password;
//			this.username = username;
//			this.phone = phone;
//			this.about = about;
			try {
			youProfileValuePairs.add(new BasicNameValuePair("user_id", UserUtil.getInfoUserLogin(context).getUser_id()));
			
			youProfileValuePairs.add(new BasicNameValuePair("user_name",username));
			youProfileValuePairs.add(new BasicNameValuePair("email", email));
			youProfileValuePairs.add(new BasicNameValuePair("password",
					StringUtil.md5(UserUtil.getInfoUserLogin(context).getPassword())));
			youProfileValuePairs.add(new BasicNameValuePair("phone", phone));
			Log.d("MD5", StringUtil.md5(password));
			String firstNameEncoded = URLEncoder.encode(firstName, "UTF-8");
			youProfileValuePairs.add(new BasicNameValuePair("first_name",
					firstNameEncoded.replace("+", "%20")));
			String lastNameEncoded = URLEncoder.encode(lastName, "UTF-8");
			youProfileValuePairs.add(new BasicNameValuePair("last_name",
					lastNameEncoded.replace("+", "%20")));
			String aboutEncoded = URLEncoder.encode(about, "UTF-8");
			youProfileValuePairs.add(new BasicNameValuePair("about", aboutEncoded.replace("+", "%20")));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void execute() throws Exception {
			String result = null;
			GardenJokesApiConnect api = new GardenJokesApiConnect(EditProfileActivity.this);
			result = api.execPost(EditProfileActivity.this,
					GardenJokesApiConnect.GROUP_U, "updateUserProfile", youProfileValuePairs);
			JSONObject jObject;
			Log.v("StringResultUpdate", result);
			if (result != null && result.length() > 0) {
				try {
					jObject = new JSONObject(result);
					JsonPaser json = new JsonPaser();
					reportError = json.getReport(result);
					report = jObject.getBoolean("is_success");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			// Check first name and last name
			if(mProgressDialog!=null){
				mProgressDialog.dismiss();
			}
//			isFirst = false;
			if (!report) {
				if (reportError.getMessage().equals("API-ERR-S0001")) {
					showErrorDialog(getString(R.string.ERR5007,getString(R.string.S01_email)));
					mEditEmail.requestFocus();
					if(mProgressDialog!=null){
						mProgressDialog.dismiss();
					}
//					isFirst = false;
				}
				if (reportError.getMessage().equals("API-ERR-S0002")) {
					Log.d("ghe qua", "qua ghe");
					showErrorDialog(getString(R.string.ERR5007,getString(R.string.S01_user_name)));
					mEditUserName.requestFocus();
				}
			} else {
				finish();
			}
			
		}
	}
	
	/**
	 * show error dialog when have error
	 * 
	 * @param msg
	 */
	public void showErrorDialog(String msg) {

		AlertDialog.Builder builder = new AlertDialog.Builder(EditProfileActivity.this);
		builder.setMessage(msg).setCancelable(true)
				.setNegativeButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
						InputMethodManager inputManager = null;
						
						 inputManager = (InputMethodManager)            
								  EditProfileActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
						 inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 1);
						 //toogle = true;
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}
}